package pl.nazaweb.imedproplus.model.facade;

import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Criteria;
import org.hibernate.Session;

public abstract class AbstractFacade<T> {

    public static final String peristanceUnitName = "pl.nazaweb_imedproplus-business-ejb_ejb_1.0-SNAPSHOTPU";
    private Class<T> entityClass;

    protected abstract EntityManager getEntityManager();

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(entity);
    }

    public void remove(List<T> entityList) {
        for (T entity : entityList) {
            remove(entity);
        }
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        String className = this.entityClass.getSimpleName();
        return getEntityManager().createNamedQuery(className + ".findAll").getResultList();
    }

    public List<T> findRange(int[] range) {
        Criteria criteria = ((Session) getEntityManager().getDelegate()).createCriteria(entityClass);
        criteria.setMaxResults(range[1] - range[0]);
        criteria.setFirstResult(range[0]);
        return criteria.list();
    }
}
